package com.zhijian.medical.util;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zhijian.medical.entity.dto.CellDto;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;


/**
 * 基站获取位置
 */
public class LacUtil {

        public static String getJSON(CellDto cellDto){
            String result = HttpRequest.get("http://api.cellocation.com:82/cell/?mcc="+cellDto.getMcc()+"&mnc="+cellDto.getMnc()+"&lac="+cellDto.getLac()+"&ci="+cellDto.getCi()+"&output=xml")
                    .header("Content-Type", "application/json")
                    .execute().body();
            return result;
        }

    public static void main(String[] args) {
        Map<String, Object> map = LacUtil.getXmlBodyContext(getJSON(null));
    }

    public static Document parseXmlString(String xmlStr){

        try{
            InputSource is = new InputSource(new StringReader(xmlStr));
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder=factory.newDocumentBuilder();
            Document doc = builder.parse(is);
            return doc;
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }


    public static Map<String,Object> getXmlBodyContext(String bodyXml){

        Map<String,Object> dataMap = new HashMap<String,Object>();

        Document doc = parseXmlString(bodyXml);
        if(null != doc){
            NodeList rootNode = doc.getElementsByTagName("response");
            if(rootNode != null){

                Node root = rootNode.item(0);
                NodeList nodes = root.getChildNodes();
                for(int i = 0;i < nodes.getLength(); i++){
                    Node node = nodes.item(i);
                    dataMap.put(node.getNodeName(), node.getTextContent());
                }
            }
        }
        return dataMap;
    }

    public static JSONObject MapToJson(CellDto cellDto){
        Map<String, Object> map = LacUtil.getXmlBodyContext(getJSON(cellDto));
        String resData = JSON.toJSONString(map, SerializerFeature.WriteMapNullValue);
        System.out.println("LAC转换地址为"+resData);
        return JSONObject.parseObject(resData);
    }



}
